package com.inspectortime.webapp.inspector.fee;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.domain.pricing.FeeCalculator;
import com.inspectortime.domain.pricing.PricingPlanType;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class FeeWizardConfirmSaveController implements Controller {

	private Repository repository;
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// Helper being used to store form fields		
		FeeWizardCommonHelper helper = FeeUtils.retrieveWizardCommonHelperFromSession(request);
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
		
		if (request.getMethod().equalsIgnoreCase("get")) {
			ModelAndView mv = new ModelAndView("inspector/fee/feeWizardConfirmSave");
			mv.addObject("helper", helper);
			mv.addObject("company", company);
			return mv;
		}
		
		// POST

		// Remove old calculators unless we are switching to advanced
		if (helper.getType()!= PricingPlanType.Advanced) {
			List<Serializable> ids = new ArrayList<Serializable>();
			for (FeeCalculator calculator : company.getFeeCalculators()) {
				ids.add(calculator.getId());
			}
			for (Serializable id : ids) {
				repository.deleteFeeCalculator(company, company.findFeeCalculatorById((String) id));				
			}
			company.save();
		}
		
		// Save changes
		company.setPricingPlanType(helper.getType());
		company.setDistanceInMilesCenterZip(helper.getDistanceInMilesCenterZip());
		company.setDistanceInMilesFeeIncreasePerMile(helper.getDistanceInMilesFeeIncreasePerMile());
		company.setDistanceInMilesLimit(helper.getDistanceInMilesLimit());
		company.getFeeCalculators().addAll(helper.createFeeCalculators());
		for (FeeCalculator calculator : company.getFeeCalculators()) {
			calculator.setSequentialId(BaseFeeWithAdjustersCalculatorFormController.nextSequentialFeeCalculatorId(company));
			calculator.setInspectorCompany(company);
		}
		company.save();
		
		String viewName = "priceHome.html";
		ModelAndView mv = new ModelAndView("redirect:" + viewName);
		return mv;
	}

}
